package LocalStorage

import (
	"KumquatDrivesServices/StorageEngine"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"github.com/sirupsen/logrus"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
	"strconv"
)

func (Le LocalEngine) SaveTempFile(uploadId StorageEngine.EngineID, userId model.SnowflakeIdType, tmpFileIndex int, tmpFile *multipart.FileHeader) error {
	bol, IsDiscardErr := uploadId.IsDiscard(userId)
	if IsDiscardErr != nil {
		logrus.Errorf("uploadId.IsDiscard(%d) err: %s", userId, IsDiscardErr)
		return IsDiscardErr
	}
	if bol {
		return StorageEngine.InvalidEngineIDErr
	}
	tmpPath := filepath.Join(Le.getTmpFilePath(uploadId), strconv.Itoa(tmpFileIndex)+ext)
	if _, err := os.Stat(tmpPath); err == nil {
		return nil
	}
	if err := utils.CreatePath(tmpPath); err != nil {
		return err
	}
	src, err := tmpFile.Open()
	if err != nil {
		return err
	}
	defer src.Close()
	out, OpenFileErr := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE, 0644)
	if OpenFileErr != nil {
		return OpenFileErr
	}
	defer out.Close()
	_, CopyErr := io.Copy(out, src)
	if CopyErr != nil {
		return CopyErr
	}
	if err = uploadId.SetTempFileSize(userId, tmpFile.Size); err != nil {
		logrus.Errorf("Error while setting temp file size: %v", err)
		return err
	}
	return nil
}
